/**
 * Created with JetBrains WebStorm.
 * User: kxl
 * Date: 13-8-28
 * Time: 下午2:21
 * 拍下商品
 */
//减法函数
function accSubtr(arg1,arg2){
    var t1 = 0, t2 = 0, m, n;
    try
    {
        t1 = arg1.toString().split(".")[1].length;
    }
    catch(e)
    {t1 = 0;}
    try
    {
        t2 = arg2.toString().split(".")[1].length;
    }
    catch(e)
    {t2 = 0;}
    with(Math)
    {
        //动态控制精度长度
        n = Math.max(t1,t2);
        m = Math.pow(10, n);
        //return (arg1  * m - arg2 * m) / m;
        return ((arg1  * m - arg2 * m) / m).toFixed(n);
    }
}
// 加法函数
function accAdd(arg1,arg2){
    var r1,r2,m;
    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
    m=Math.pow(10,Math.max(r1,r2))
    return (arg1*m+arg2*m)/m
}


$(function () {
    if ($("#jf_default").val() == 1 && $("#J_UsePoints").length>0) {
        $("#J_UsePoints").attr('checked',true);
        if($('#J_UsePoints').length>0){
            updateJf();
        }
    }

    var mask = '<div class="tc-mask"></div>';

    if ($("#address_count").val() == 0) {
        $("body").append($(mask));
    }

    function initAddress() {

        var args = {
            "_defaultValue": {
                "province": "请选择省份...",
                "city": "请选择市...",
                "country": "请选择县/区..."
            },
            "_elements": {
                "province": $("#province"),
                "city": $("#city"),
                "country": $("#country")
            },
            "_ids":{
                "provinceid":0,
                "cityid": 0,
                "districtid":0
            } ,
            "_pid": 1
        };

        var region = new Region(args);

        $("#province").change(function () {
            region.changeEvent(this);
        });
        $("#city").change(function () {
            region.changeEvent(this);
        });

        $("input[name='addrZip']").keyup(function(){
            var val = t = $(this).val();
            var reg = new RegExp("^[0-9]*$");
            if(!reg.test(t)){val  = '' }
            if(t != '') {
                if(val.length > 6){
                    val = val.substr(0,6);
                }
                $(this).val(val)
            }
        })

        $("input[name='addrMobi']").keyup(function(){
            var val = t = $(this).val();
            var reg = new RegExp("^[0-9]*$");
            if(!reg.test(t)){val  = '' }
            if(t != '') {

                if(val.length > 11){
                    val = val.substr(0,11);
                }
                $(this).val(val)
            }
        })
        $("input[name='addrArea']").keyup(function(){
            var val = t = $(this).val();
            var reg = new RegExp("^[0-9]*$");
            if(!reg.test(t)){val  = '' }
            if(t != '') {
                if(val.length > 5){
                    val = val.substr(0,5);
                }
                $(this).val(val)
                }
        })
        $("input[name='addrNum']").keyup(function(){
            var val = t = $(this).val();
            var reg = new RegExp("^[0-9]*$");
            if(!reg.test(t)){val  = '' }
            if(t != '') {
                if(val.length > 8){
                    val = val.substr(0,8);
                }
                $(this).val(val)
            }
        })
        $("input[name='addrExt']").keyup(function(){
            var val = t = $(this).val();
            var reg = new RegExp("^[0-9]*$");
            if(!reg.test(t)){val  = '' }
            if(t != '') {
                if(val.length > 8){
                    val = val.substr(0,8);
                }
                $(this).val(val)
            }
        })
    }
    
    function newAddress() {
        var createAddr = $('.createAddr'), create_addr = $('.create_addr');
        createAddr.click(function () {
            var reqUrl = $(this).attr("gdata-url");
            $.get(reqUrl, function (data) {
                $('body').append($(mask));
                create_addr.append(data);
                initAddress();
            });
        });
        
        $(".deftip2").click(function(event){
        	//createAddr.click();
            var reqUrl = $('.createAddr').attr("gdata-url");
            reqUrl = reqUrl.replace("newAddress","editAddress")+"&id="+$(this).parents(".addr").attr("data-id");
            $.get(reqUrl, function (data) {
                $('body').append($(mask));
                $('.create_addr').append(data.string);
                var args = {
                    "_defaultValue": {
                        "province": "请选择省份...",
                        "city": "请选择市...",
                        "country": "请选择县/区..."
                    },
                    "_elements": {
                        "province": $("#province"),
                        "city": $("#city"),
                        "country": $("#country")
                    },
                    "_ids":{
                        "provinceid":0,
                        "cityid": 0,
                        "districtid":0
                    } ,
                    "_pid": 1
                };

                var region = new Region(args);

                $("#province").change(function () {
                    region.changeEvent(this);
                });
                $("#city").change(function () {
                    region.changeEvent(this);
                });    				 
               
                /*初始化地址*/
                if (data.msg.province) {
                    var intProvinceId = data.msg.provinceid;
                    var intCityId = data.msg.cityid;
                    var intCountryId = data.msg.districtid;
                    var checkVObj =
                    {
                        'province': {'pid': 1, 'region_id': intProvinceId},
                        'city': {'pid': intProvinceId, 'region_id': intCityId},
                        'country': {'pid': intCityId, 'region_id': intCountryId}
                    };
                    region.upSelect(checkVObj);
                }
            },"json");
        	event.stopPropagation();
        })

        //提交新地址
        $('body').delegate(".primary", "click", function (check) {
            // window.location.reload();
            // return false;
            var reqUrl = $("#winNewAddress").attr("action");
            var flag = true;
            var add = $('#country').val();
            var code = $.trim($('[name=addrZip]').val());//邮编
            var addr = $.trim($('#amaddr').val());//地址
            var name = $.trim($('#amname').val());//姓名
            var addrArea = $.trim($('[name=addrArea]').val());//区号
            var addrNum = $.trim($('[name=addrNum]').val());//电话号码
            var addrExt = $.trim($('[name=addrExt]').val());//分机
            var tel = $.trim($("#ammobi").val());
            if (add == 0) {
                error("请选择地址", $("#country").parents("td"));
                flag = false;
            } else {
                $("#country").parents("td").removeClass('am-err').find(".tc-feedback").remove();
            }
            //号码
            /*if (addrArea == '' && addrNum == '' && tel == '' && addrExt=='') {
                error("电话和手机不能都为空", $("#ammobi").parents("td"));
                $("[name=addrArea]").parents("td").find(".tc-feedback").remove();
                flag = false;
            }*/
            if (addrArea != "" && tel == '') {
                if (!(/^0[1-9][0-9]{1,2}$/g.test(addrArea))) {
                    error("区号必须由3到5位数字构成", $("[name=addrArea]").parent("td"));
                    $("#ammobi").parent("td").removeClass('am-err').find(".tc-feedback").remove();
                    flag = false;
                } else {
                    if (addrNum == "") {
                        error("请填写正确的电话", $("[name=addrArea]").parent("td"));
                        $("#ammobi").parent("td").removeClass('am-err').find(".tc-feedback").remove();
                        flag = false;
                    } else {
                        if (!(/^[1-9]\d{6,7}$/g.test(addrNum))) {
                            $("[name=addrArea]").parent("td").removeClass('am-err').find(".tc-feedback").remove();
                            error("请填写正确的电话", $("[name=addrArea]").parent("td"));
                            flag = false;
                        } else {
                            if (addrExt.length > 0 && !(/^[0-9]\d{1,7}$/g.test(addrExt))) {
                                error("请填写正确的电话", $("[name=addrArea]").parent("td"));
                                $("#ammobi").parent("td").removeClass('am-err').find(".tc-feedback").remove();
                                flag = false;
                            }else{
                                $("[name=addrArea]").parent("td").removeClass('am-err').find(".tc-feedback").remove();
                            }
                        }
                    }
                }
            }


            if (tel == '') {
                error("此项必填", $("#ammobi").parent("td"));
                flag = false;
            } else {
                if (!(/^1\d{10}$/g.test(tel)) && !(/^\d?861\d{10}$/g.test(tel))) {
                    error("手机号码格式不对", $("#ammobi").parent("td"));
                    $("[name=addrArea]").parent("td").removeClass('am-err').find(".tc-feedback").remove();
                    flag = false;
                } else {
                    $("#ammobi").parent("td").removeClass('am-err').find(".tc-feedback").remove();
                }
            }

            if (tel != '') {
                if (addrArea != "") {
                    if (!(/^0[1-9][0-9]{1,2}$/g.test(addrArea))) {
                        error("区号必须由3到5位数字构成", $("[name=addrArea]").parent("td"));
                        $("#ammobi").parent("td").removeClass('am-err').find(".tc-feedback").remove();
                        flag = false;
                    } else {
                        if (addrNum == "") {
                            error("请填写正确的电话", $("[name=addrArea]").parent("td"));
                            $("#ammobi").parent("td").removeClass('am-err').find(".tc-feedback").remove();
                            flag = false;
                        } else {
                            if (!(/^[1-9]\d{6,7}$/g.test(addrNum))) {
                                $("[name=addrArea]").parent("td").find(".tc-feedback").remove();
                                error("请填写正确的电话", $("[name=addrArea]").parent("td"));
                                flag = false;
                            } else {
                                if (addrExt.length > 0 && !(/^[0-9]\d{1,7}$/g.test(addrExt))) {
                                    error("请填写正确的电话", $("[name=addrArea]").parent("td"));
                                    $("#ammobi").parent("td").removeClass('am-err').find(".tc-feedback").remove();
                                    flag = false;
                                }else{
                                    $("[name=addrArea]").parent("td").removeClass('am-err').find(".tc-feedback").remove();
                                }
                            }
                        }
                    }
                } else {
                    $("[name=addrArea]").parent("td").removeClass('am-err').find(".tc-feedback").remove();
                }
            }
            if (addrNum != '') {
                if (!(/^[1-9]\d{6,7}$/g.test(addrNum))) {
                    $("[name=addrArea]").parent("td").find(".tc-feedback").remove();
                    error("请填写正确的电话", $("[name=addrArea]").parent("td"));
                    $("#ammobi").parent("td").removeClass('am-err').find(".tc-feedback").remove();
                    flag = false;
                } else if (addrArea == "") {
                    if (!(/^0[1-9][0-9]{1,2}$/g.test(addrArea))) {
                        error("请填写由3到5位数字构成的区号", $("[name=addrArea]").parent("td"));
                        $("#ammobi").parent("td").removeClass('am-err').find(".tc-feedback").remove();
                        flag = false;
                    }
                }
            }
            if (addrExt.length > 0 && !(/^[0-9]\d{1,7}$/g.test(addrExt))) {
                if (addrArea == "" || addrNum == "") {
                    error("请填写正确的电话", $("[name=addrArea]").parent("td"));
                    flag = false;
                }
            }
            //邮编
            if (code!= '' &&  !(/^\d{6}$/g.test(code))) {
                error("邮政编码填写有误，请输入6位邮政编码", $('[name=addrZip]').parent("td"));
                flag = false;
            } else {
                clearError($('[name=addrZip]').parent("td"));
            }
            //地址
            if (addr == '') {
                error("此项必填", $("#amaddr").parent("td"));
                flag = false;
            } else if (addr.length < 4 || addr.length > 60) {
                error("地址最少要4个字，最多不能超过60个字", $("#amaddr").parent("td"));
                flag = false;
            } else if (/^[0-9]+$/.test(addr)) {
                error("地址不能全是数字，请重新填写", $("#amaddr").parent("td"));
                flag = false;
            } else if (/^[a-z]+$/.test(addr) || /^[A-Z]+$/.test(addr)) {
                error("地址不能全是英文字母，请重新填写", $("#amaddr").parent("td"));
                flag = false;
            } else {
                clearError($("#amaddr").parent("td"));
            }
            //name
            if (name == '') {
                error("此项必填", $('#amname').parents("td"));
                flag = false;
            } else {
                clearError($('#amname').parent("td"));
            }

            /*if (tel == '') {
                error("此项必填", $('#ammobi').parents("td"));
                flag = false;
            } else {
                clearError($('#ammobi').parent("td"));
            }*/
            //            请求数据为Form#winNewAddress 中的input值, 键值对分别为Input的name于vaule
            if (!flag) {
                check.preventDefault();
            } else {
                check.preventDefault();
                var obj = $("#winNewAddress").serialize();
                $.ajax({
                    url: reqUrl,
                    dataType: "json",
                    type: "POST",
                    data: obj,
                    success: function (data) {
                        if (data.err == 0) {
                            //var frmReset = $('#resetAddress');
                            $('#resetAddress').children('input[name="addressId"]').val(data.data.addressId);
                            $('#resetAddress').submit();
                            //frmReset.find('[name=addressId]').val();
                        } else if (data.err == 1) {
                            alert('新增地址失败')
                        }
                    }
                });
            }
        })
    }

    newAddress();
    //关闭取消
    $('body').delegate(".hide,.tc-popup-hide", "click", function () {
        $('.addrmaker').remove();
        $(".tc-mask").hide();
    });

    /*设置为默认地址*/
    function DefaultAddress(obj) {
        this.defaultBtn = obj.find(".setdefault");
        var _this = this;
        obj.hover(function () {
            _this.Menter($(this));
        }, function () {
            _this.Mout($(this));
        });
        obj.click(function () {
            _this.Click($(this));
        });
        this.defaultBtn.click(function () {
            _this.setDefaultAddress($(this));
            location.reload([false]);   
            return false;
        });
    }

    DefaultAddress.prototype = {
        Menter: function (obj) {
            obj.addClass("addr-active");
            if (obj.hasClass("addr-cur") && !obj.hasClass("addr-def")) {
                obj.addClass("addr-set");
            }
        },
        Mout: function (obj) {
            obj.removeClass("addr-active");
            if (obj.hasClass("addr-cur") && !obj.hasClass("addr-def")) {
                obj.removeClass("addr-set");
            }
        },
        Click: function (obj) {
            $(".since li").removeClass("choosed");
            obj.addClass("addr-cur").siblings().removeClass('addr-cur addr-set');
            if (!obj.hasClass("addr-def")) {
                obj.addClass("addr-set")
            }
            var frmAddress = $('#resetAddress'), curAddrId = obj.attr('data-id');
            frmAddress.find('input[name=addressId]').val(curAddrId);
            frmAddress.submit();
        },
        setDefaultAddress: function (obj) {
            var reqUrl = obj.attr("href");
            $.get(reqUrl, function (data) {
                if (data.err == 0) {
                    obj.parents(".addr").addClass("addr-def").removeClass("addr-set").siblings().removeClass("addr-def");
                    alert("操作成功");
                } else if (data.err = 1) {
                    alert("操作失败")
                }
            }, "json");
        }
    };
    var defaultAdd = new DefaultAddress($("#J_addresses .addr"));


    function error(txt, target) {
        var errMsg = '<div class="tc-feedback"><div class="tc-feedback-inner"><div class="tc-feedback-con tc-feedback-error"><p>' + txt + '</p><s class="tc-feedback-icon"></s></div></div></div>';
        if (target.find(".tc-feedback").length) {
            target.find(".tc-feedback").remove();
        }
        target.append(errMsg);
        target.addClass('am-err');
    }

    function clearError(target) {
        target.find(".tc-feedback").remove();
        target.removeClass('am-err');
    }

    function PointsHtml(currentMoney){
        //获取当前积分
        var basepoints = $.trim($('#J_ActualBase').val());
        var basegrade = $.trim($('#J_ActualGrade').val());
        if(basepoints != ''){
            basepoints = parseInt(basepoints);
        }else{
            basepoints = 0;
        }
        if(basegrade != ''){
            basegrade = parseInt(basegrade);
        }else{
            basegrade = 0;
        }
        var currentPoints = Math.round(currentMoney*basegrade)+basepoints;
        $('#J_ObtainPoints').html(currentPoints);
    }
});


//模拟下拉框
$('.tc-select').click(function (e) {
    e.stopPropagation();
    var width = $(this).width();
    $('.tc-select').removeClass("tc-select-open");
    $(this).addClass("tc-select-open");
    $(this).find(".tc-select-options").width(width);
});
$(document).click(function () {
    $('.tc-select').removeClass('tc-select-open')
});
$('.tc-select-option').hover(function () {
    $(this).addClass("tc-select-option-active");
}, function () {
    $(this).removeClass("tc-select-option-active");
});

$('.tc-select-option').click(function (e) {
    e.stopPropagation();
    var lineTr = $('tr[data-order-total]') , storeId = lineTr.attr('data-store-id');
    var val = $(this).html();
    var par_sele = $(this).parents(".tc-select");
    var url = par_sele.attr('data-set-url');
    var source = par_sele.attr('data-source');
    var orderSn = $('input[name=orderSn]').val(); //订单sn
    var path = $(this).attr('data-mail-path'); //路径
    var postage = parseFloat($(this).attr('data-value')); //运费总价
    par_sele.removeClass("tc-select-open");

    // 套餐邮资更改
    if (source == 'package' || source == 'directly') {
        $.post(url, {'orderSn': orderSn, 'mailPath': path, 'storeId': storeId}, function (response) {
            if (response['err'] != 0) {
                alert(response['message']);
            } else {
                par_sele.find(".tc-select-label").html(val);
                par_sele.find(".tc-select-label").attr('data-value', postage);

                var total = parseFloat(lineTr.attr('data-order-total')); //套餐总价
                var gross = total + postage; // 应付套餐总价(含运费)

                // var amt_coupons = parseFloat($('#couponsList').find('option:selected').val()); //优惠券抵扣金额
                var amt_coupons = parseFloat($('#coupcount_' + storeId + ']').val()); //优惠券抵扣金额
                amt_coupons = amt_coupons ? amt_coupons : 0;

                $('#J_BundleSum_'+storeId).html(gross.toFixed(2)); //更新当前店铺应付金额

                updateLq();
                var currentMoney = $('#J_ActualPaid').text();

                PointsHtml(currentMoney);
            }
        }, 'json');
    }


});

/**购物车运费选择*/
$('select[id^=postage_opt]').change(function () {
    var lineTr = $(this).parents('tr[data-order-total]');
    var storeId = lineTr.attr('data-store-id'), postage = parseFloat($(this).val()), orderTotal = parseFloat(lineTr.attr('data-order-total'));


    //更新邮资
    var orderSn = $('input[name=orderSn]').val();
    var path = $(this).find('option:selected').attr('data-mail-path');
    var url = $(this).attr('data-set-url');
    $.post(url, {'orderSn': orderSn, 'storeId': storeId, 'mailPath': path}, function (data) {
        if (data['err'] != 0) {
            alert(data['message']);
        } else {
            $('#G_Postage_' + storeId).html(postage.toFixed(2)); //更新邮资标签
            var amt_deduction = parseFloat($('#J_Discharge').html()); //积分抵扣金额
            amt_deduction = amt_deduction ? amt_deduction : 0
            var amt_coupons = parseFloat($('#coupcount_' + storeId).html()); //优惠券金额
            amt_coupons = amt_coupons ? amt_coupons : 0;

            var orderSum = orderTotal + postage - amt_coupons;
            if (orderSum <= postage) orderSum = postage;
            $('#J_BundleSum_' + storeId).html(orderSum.toFixed(2)); //更新当前店铺订单总价
            updateLq();
        }
    }, 'json');
})

/** 2016-11 版 店铺优惠券选项 */
/*$(".whatisthis > .d9").click(function(event){
    var orderSn = $('input[name=orderSn]').val();
    var url = $(".money_button").attr("data-bundle-url");
    var storeId = $(this).parents(".discountCouponActiveBox").find(".money_button").attr('data-storeid');

    if($(this).hasClass("use-card")){
        $(this).removeClass("use-card").html("使用");
        $("#coupcount_"+storeId).parents(".money_button").html('<font style="font-size:12px;font-weight:normal;line-height: 28px;" id="coupcount_'+storeId+'">使用优惠券</font>');
        couponsId = 0;
    } else{
        $(this).html("已选择").addClass("use-card");
        $(this).parents(".whatisthis").siblings().find(".d9").removeClass("use-card").html("使用")
        $("#coupcount_"+storeId).parents(".money_button").html('￥<font style="font-size:20px;font-weight:700;line-height: 28px;" id="coupcount_'+storeId+'">使用优惠券</font>');
        couponsId = $(this).parents(".whatisthis").attr("data-id")
    }

    var lineTr = $(this).parents('tr[data-order-total]');
    var orderTotal = parseFloat(lineTr.attr('data-order-total')); //店铺订购商品总价
    var postage = parseFloat($('#G_Postage_' + storeId).html()); //统一标准运费

    if (!lineTr[0]) {
        //立即购买
        orderTotal = parseFloat($('tr[data-order-total]').eq(0).attr('data-order-total'));
        postage = parseFloat($('.tc-selected').attr('data-value'));
    }

    $.post(url, {'orderSn': orderSn, 'storeId': storeId, 'couponsId': couponsId}, function (data) {
        if (data['err'] != 0) {
            alert(data['message']);
        } else {
            var couponsAmt = parseFloat(data['data']);
            if(couponsId != 0){
                $("#coupcount_"+storeId).html(couponsAmt.toFixed(2));
                $(".dis_coupcount_"+storeId).html("-"+couponsAmt.toFixed(2))
            }

            // 更新当前店铺 金额
            var orderSum = orderTotal + postage - couponsAmt;
            if (orderSum <= postage) orderSum = postage;
            var sp = $(".shopGross");
            if(!sp[0]){
                $('#J_BundleSum_' + storeId).html(orderSum.toFixed(2)); //更新当前店铺订单付款总额标签
            } else{
                $(".shopGross").html(orderSum.toFixed(2));//立即购买
            }

            //更新礼品券
            updateLq();

            currentMoney = $('#J_ActualPaid').text();

            //获取当前积分
            var basepoints = $.trim($('#J_ActualBase').val());
            var basegrade = $.trim($('#J_ActualGrade').val());
            if(basepoints != ''){
                basepoints = parseInt(basepoints);
            }else{
                basepoints = 0;
            }
            if(basegrade != ''){
                basegrade = parseInt(basegrade);
            }else{
                basegrade = 0;
            }
            var currentPoints = Math.round(currentMoney*basegrade)+basepoints;
            $('#J_ObtainPoints').html(currentPoints);

        }
    },"json")
    event.stopPropagation();
})*/

function whatisthis(doc){
    $This = $(doc);

    if($This.hasClass("disables")){
        return;
    }
    var orderSn = $('input[name=orderSn]').val();
    var url = $(".money_button").attr("data-bundle-url");
    var storeId = $This.parents(".discountCouponActiveBox").find(".money_button").attr('data-storeid');
    var mbtn = $("#coupcount_"+storeId).parents(".money_button");

    if($This.hasClass("use-card")){
        $This.removeClass("use-card").html("使用");
        mbtn.html('<font style="font-size:18px;font-weight:700;line-height: 28px;" id="coupcount_'+storeId+'">使用优惠券</font>');
        couponsId = 0;
        $('.discoup').css({'display':'none'});//隐藏不显示优惠券
    } else{
        $This.html("已选择").addClass("use-card");
        $This.parents(".whatisthis").siblings().find(".d9").removeClass("use-card").html("使用")
        //$("#coupcount_"+storeId).parents(".money_button").html('￥<font style="font-size:20px;font-weight:700;line-height: 28px;" id="coupcount_'+storeId+'">使用优惠券</font>');
        couponsId = $This.parents(".whatisthis").attr("data-id");
        $('.discoup').css({'display':'block'});//隐藏不显示优惠券
        $This.parents('.usepresent').hide();
    }

    var lineTr = $This.parents('tr[data-order-total]');
    var orderTotal = parseFloat(lineTr.attr('data-order-total')); //店铺订购商品总价
    var postage = parseFloat($('#G_Postage_' + storeId).html()); //统一标准运费

    if (!lineTr[0]) {
        //立即购买
        orderTotal = parseFloat($('tr[data-order-total]').eq(0).attr('data-order-total'));
        postage = parseFloat($('.tc-selected').attr('data-value'));
    }

    $.post(url, {'orderSn': orderSn, 'storeId': storeId, 'couponsId': couponsId}, function (data) {
        if (data['err'] != 0) {
            alert(data['message']);
        } else {
            var couponsAmt = parseFloat(data['data']);
            if(couponsId != 0){
                $("#coupcount_"+storeId).html('&#65509;' + couponsAmt.toFixed(2));
                $(".dis_coupcount_"+storeId).html("-"+couponsAmt.toFixed(2))
            }

            // 更新当前店铺 金额
            var orderSum = orderTotal + postage - couponsAmt;
            if (orderSum <= postage) orderSum = postage;
            var sp = $(".shopGross");
            if(!sp[0]){
                $('#J_BundleSum_' + storeId).html(orderSum.toFixed(2)); //更新当前店铺订单付款总额标签
            } else{
                $(".shopGross").html(orderSum.toFixed(2));//立即购买
            }

            //更新礼品券
            updateLq();

            currentMoney = $('#J_ActualPaid').text();

            //获取当前积分
            var basepoints = $.trim($('#J_ActualBase').val());
            var basegrade = $.trim($('#J_ActualGrade').val());
            if(basepoints != ''){
                basepoints = parseInt(basepoints);
            }else{
                basepoints = 0;
            }
            if(basegrade != ''){
                basegrade = parseInt(basegrade);
            }else{
                basegrade = 0;
            }
            var currentPoints = Math.round(currentMoney*basegrade)+basepoints;
            $('#J_ObtainPoints').html(currentPoints);

        }
    },"json")
    event.stopPropagation();
}



//不使用优惠券
$(".discoup").click(function(){
    if($(".use-card").length > 0){
        $(".use-card").trigger("click");
    }
})

function toggleLq(enable){
    var source = getQueryString("source");
    var lqid = $("[name='lqid']").val();
    var scroll_top = $(document).scrollTop();
    var url = "/bBVerifyOrder.html&source="+source;
    if (enable == false) {
        $("[name='lqid']").remove();
        $("#J_orderForm").append("<input type='hidden' value='1' name='notneed_default_lq'>");
    }

    $("#J_orderForm").attr("action", url);
    //原先这几个值放在resetAddress表单里了  现在要复制到J_orderForm表单
    if (source == 'directly') {
        var goods_id = $("[name='goods_id']").val();
        $("#J_orderForm").append("<input type='hidden' value='"+goods_id+"' name='goods_id'>");
        var buyQuantity = $("[name='buyQuantity']").val();
        $("#J_orderForm").append("<input type='hidden' value='"+buyQuantity+"' name='buyQuantity'>");
    }
    $("#J_orderForm").append("<input type='hidden' value='"+scroll_top+"' name='scroll_top'>");
    $("#J_orderForm").submit();
}

$(".money_button").click(function(event){
    $(this).parent().siblings(".usepresent").slideDown(200);
    event.stopPropagation();
})
//==============  发票相关  ======================
var uid = $("input[name='uid']").val();


//发票弹框中的切换
$("#j_bill span").click(function() {
	var m=$(this).index();

    if($(this).attr("key") != 0){
	    var type = $(this).attr("key");
	    if(type == 2){
	        // 隐藏 发票内容中 除了明细 其它的选项
	        $(".pop-dl").find("dd:not(':first')").hide();
			$(".qyfpbz").text('');
	    }else if(type==4){
			$(".qyfpbz").text('（注：开企业抬头发票须填写纳税人识别号，以免影响报销！）');
			$(".pop-dl").find("dd").show();
		} else {
	        $(".pop-dl").find("dd").show();
			$(".qyfpbz").text('');
	    }
	    $.post("/index.php?app=member/BVerifyOrder&act=getInvoice",{"uid":uid,"type":type},function(data){
	        if(data){
	            $("input[name='invoice_id']").val(data.ccnid)
                $("input[name='type']").val(data.ccn02)
	            if(parseInt(type) == 2){
	                $("input[name='company']").val(data.ccn03);
	                $("input[name='texpayer']").val(data.ccn04);
	                $("input[name='address']").val(data.ccn05);
	                $("input[name='tel']").val(data.ccn06);
	                $("input[name='bank']").val(data.ccn07);
	                $("input[name='card']").val(data.ccn08);
	            }else if(parseInt(type) == 4){
					$("input[name='title"+type+"']").val(data.ccn03);
                    $(".pop-dl.d"+type+" dd").removeClass("active");
                    $(".pop-dl.d"+type+" dd[key="+data.ccn04+"]").addClass("active");
					$("input[name='qycode']").val(data.ccn10);
                    var content = $(".pop-dl.d"+type+" dd.active").attr("key"); // 发票内容
					
				} else {
	                $("input[name='title"+type+"']").val(data.ccn03);
                    $(".pop-dl.d"+type+" dd").removeClass("active");
                    $(".pop-dl.d"+type+" dd[key="+data.ccn04+"]").addClass("active");
                    var content = $(".pop-dl.d"+type+" dd.active").attr("key"); // 发票内容
	            }
	        } else {
	            $("input[name='invoice_id']").val(0)
	        }
	    }, 'json')
	} else {
        $(".pop-dl.d"+type+" dd:first").addClass("active");
	    $("input[name='invoice_id']").val(0)
	}

	$(this).addClass("active").siblings().removeClass("active");
	$(this).addClass("saveFOn").siblings().removeClass("saveFOn");
	$(this).parent().siblings(".ul-content").children().eq($(this).index()).addClass("active").siblings().removeClass("active");

	var fp_btn=$(this).parents(".layui-layer-page");
	var wH=$(window).height();
	var boxH=fp_btn.height()+10;
	var posTop=(wH-boxH)/2;
	fp_btn.css("top",posTop);
})

$(".iClose",".popup_content_bill").click(function(){
	hidePop();
})


// 隐藏窗口
function closedPop() {
    $("input[name='invoice_id']").val($("input[name='invoice_id']").attr("old"));
    hidePop();
}

// 弹出窗口
$(function(){
    $("#selectInvoice").click(function(){
		$("#j_bill").children().eq(0).addClass("saveFOn").siblings().removeClass("saveFOn");
		$(".fill_con").find("li").eq(0).addClass("active").siblings("li").removeClass("active");
        $(".ul-content li").eq(0).addClass("active").siblings("li").removeClass("active");
        var type = $("input[name='type']").val();
        $("#j_bill span[key="+type+"]").click();
		showLayer(750,"popup_content_bill","",function(){
		});
    });

    //选择礼品券后  保持原来高度
    var scroll_top = $("input[name='scroll_top']").val();
    if (scroll_top) {
        $(window).scrollTop(scroll_top);
    }
    
})

$(".closed, .reset").click(closedPop);

// 选项卡事件
$("ul.bar>li").click(function(){
    $(this).addClass("active").siblings("li").removeClass("active");

    var m = $(this).index()
    $("ul.ul-content>li").eq(m).addClass("active").siblings("li").removeClass("active");

    $("input[name='type']").val($(this).attr("key"))
    //$("input[name='invoice_cont']").val(1)
    $(".pop-dl > dd").eq(0).addClass("active").siblings("dd").removeClass("active");

    if($(this).attr("key") != 0){
        var type = $(this).attr("key");
        if(type == 2){
            // 隐藏 发票内容中 除了明细 其它的选项
            $(".pop-dl").find("dd:not(':first')").hide();
        } else {
            $(".pop-dl").find("dd").show();
        }
        $.post("/index.php?app=member/BVerifyOrder&act=getInvoice",{"uid":uid,"type":type},function(data){
            if(data){
                $("input[name='invoice_id']").val(data.ccnid)
                if(parseInt(type) == 2){
                    $("input[name='company']").val(data.ccn03)
                    $("input[name='texpayer']").val(data.ccn04)
                    $("input[name='address']").val(data.ccn05)
                    $("input[name='tel']").val(data.ccn06)
                    $("input[name='bank']").val(data.ccn07)
                    $("input[name='card']").val(data.ccn08)
                } else {
                    $("input[name='title']").val(data.ccn03)

                }
            } else {
                $("input[name='invoice_id']").val(0)
            }
        }, 'json')
    } else {
        $("input[name='invoice_id']").val(0)
    }
})

//发票内容选择
$(".pop-dl > dd").click(function(){
    $(this).addClass("active").siblings("dd").removeClass("active");
    if($(this).attr("key") == 7){ //自定义
        $(this).html("<input class='inf' type='text' name='inf' value=''/> ");
        $("input[name='inf']").focus();
    } else{
        $(this).parents("dl.pop-dl").find("dd:last").text("自定义")
    }
})


// ==============
$(".iSaveF").click(function(){
    // 保存当前所选的 并关闭弹窗
    $obj = $(".popup_content_bill span.active");
    var type = $obj.attr("key"); //发票类型 普通发票|增值税发票|无需发票
    var id = $("input[name='invoice_id']").val();// 发票ID
    var cont = ''; // 发票自定义内容
    if(type < 1) { //无需发票
        $("input[name='invoice_id']").val(0).attr("old",0);
        $("span.labs").text("暂不需要");
        $.post("/index.php?app=member/BVerifyOrder&act=saveInvoice",{"id":0,'uid':uid,"type":type},function(data){
            alert("保存成功")
        });
        closedPop();
    }else if(type == 1 || type == 3) { //普通发票 收据
        if($("input[name='title"+type+"']").val().length<1) {
            alert("请填写发票抬头！")
            return false;
        }
        var content = $(".pop-dl.d"+type+" dd.active").attr("key"); // 发票内容
        var Tmp = 0;
        $(this).parents(".center").find("li.active .pop-dl>dd").each(function(){
            if($(this).hasClass("active"))
                Tmp = $(this).attr("key")
        })

        $("input[name='invoice_cont']").val(Tmp)

        if(Tmp == 7){ //自定义发票
            if($("input[name='inf']").val().length<1){
                $("input[name='inf']").focus();
                alert("请填写自定义内容！")
                return false;
            } else {
                cont = $("input[name='inf']").val();
                $("input[name='invoice_cont']").val(cont)
            }
        }
        var title = $("input[name='title"+type+"']").val();

        //增加或者修改发票信息
        $.post("/index.php?app=member/BVerifyOrder&act=saveInvoice",{"id":id,"title":title,'uid':uid,"type":type,"cont":content},function(data){
            closedPop();
            if(data>0){
                $("input[name='invoice_id']").val(data).attr("old",data);
                if (type == 1) {
                    $("span.labs").text("个人普通发票");
                } else {
                    $("span.labs").text("收据");
                }
                
                alert("保存成功")
            } else {
                alert("操作失败，请稍后再试！")
            }
        })
    }else if(type==4){
		  if($("input[name='title"+type+"']").val().length<1) {
            alert("请填写发票抬头！")
            return false;
		}
		  if($("input[name='qycode']").val().length<1){
			  alert("请填写纳税人识别号或统一社会信用代码");
			  return false;
		  }
		  var content = $(".pop-dl.d"+type+" dd.active").attr("key"); // 发票内容
		 var Tmp = 0;
        $(this).parents(".center").find("li.active .pop-dl>dd").each(function(){
            if($(this).hasClass("active"))
                Tmp = $(this).attr("key")
        })

        $("input[name='invoice_cont']").val(Tmp)

        if(Tmp == 7){ //自定义发票
            if($("input[name='inf']").val().length<1){
                $("input[name='inf']").focus();
                alert("请填写自定义内容！")
                return false;
            } else {
                cont = $("input[name='inf']").val();
                $("input[name='invoice_cont']").val(cont)
            }
        }
        var title = $("input[name='title"+type+"']").val();//发票抬头
		var code=$("input[name='qycode']").val();//纳税人识别号或统一社会信用代码
		        //增加或者修改发票信息
        $.post("/index.php?app=member/BVerifyOrder&act=saveInvoice",{"id":id,"title":title,'uid':uid,"type":type,"cont":content,code:code},function(data){
            closedPop();
            if(data>0){
                $("input[name='invoice_id']").val(data).attr("old",data);
               
                    $("span.labs").text("企业普通发票");
               
                
                alert("保存成功")
            } else {
                alert("操作失败，请稍后再试！")
            }
        })
		  
		} else {// 增值税发票
        var company = $("input[name='company']").val();
        var texpayer = $("input[name='texpayer']").val();
        var address = $("input[name='address']").val();
        var tel = $("input[name='tel']").val();
        var bank = $("input[name='bank']").val();
        var card = $("input[name='card']").val();

        if(company.length<1) {
            $("input[name='company']").focus()
            alert("请填写公司名称")
            return false;
        }
        /*if(texpayer.length<1 || !/^[0-9a-zA-Z-_]*$/.test(texpayer)) {
            $("input[name='texpayer']").focus()
            alert("纳税人识别码填写错误")
            return false;
        }*/
        if(address.length<1) {
            $("input[name='address']").focus()
            alert("请填写注册地址")
            return false;
        }
        /*if(tel.length<1 || !/^0\d{2,3}-?\d{7,8}$/.test(tel)) {
            $("input[name='tel']").focus()
            alert("请填写正确的注册电话")
            return false;
        }*/
        if(bank.length<1) {
            $("input[name='bank']").focus()
            alert("请填写开户银行")
            return false;
        }
        /*if(card.length<1 || !/^([a-zA-Z0-9]){8,40}$/g.test(card)) {
            $("input[name='card']").focus()
            alert("请填写正确的银行账户")
            return false;
        }*/

        $("input[name='invoice_cont']").val(1)

        //增加或者修改发票信息
        $.post("/index.php?app=member/BVerifyOrder&act=saveInvoice",{"id":id,'address':address,'tel':tel,'bank':bank,'card':card,'company':company,'texpayer':texpayer,'uid':uid,"type":type},function(data){
            closedPop();
            if(data>0){

                $("input[name='invoice_id']").val(data).attr("old",data);
                $("span.labs").text("增值税发票");
                alert("保存成功")
            } else {
                alert("操作失败，请稍后再试！")
            }
        })
    }
})

/*
 * 购买 计算 公式
 * 1级 店铺优惠券   2级 点券卡   3级 积分
 * 实付款 = 店铺1合计（商品总价+运费-优惠券抵扣） + 店铺2合计 + .. - 点券卡优惠 - 积分抵扣
 *
 * 积分抵扣金额计算  = {店铺1合计（商品总价-优惠券抵扣）+ 店铺2合计 + .. - 点券卡抵扣}/rate
 */
var $jfUse = $("input[name='jfUse']");//积分使用
var _rate = $(".costPoint").attr("data-rate"); // 积分兑换比例
var $J_ActualPaid = $("#J_ActualPaid"); //总价

function countAll(){
    var $dkqUse = $(".presentItem").find(".icon2:visible"); // 新版礼品券dom对象

    //更新计算应付金额
    var paidAmount = 0;
    $('[id^=J_BundleSum_]').each(function () {
        paidAmount += parseFloat($(this).html());
    })


    // 礼品券抵扣
    if($dkqUse.length > 0){
        paidAmount -= $("#cdkq").val()*1;
    }

    // 积分抵扣
    if($jfUse.is(":checked")){
        paidAmount -= $(".costPoint").val()*_rate;
    }

    $J_ActualPaid.text(paidAmount.toFixed(2));

}

$jfUse.click(updateJf) //积分
$(".costPoint").change(function(){
    var $dkqUse = $(".presentItem").find(".icon2:visible"); // 新版礼品券dom对象

    var _jf_rate = $(".costPoint").attr("data-rate")
    var _jf_max = $(".usablePoints").text();

    var paidAmount = 0;
    $('[id^=J_BundleSum_]').each(function () {
        paidAmount += parseFloat($(this).html());
    })

    //直接购买时一件商品的运费计算
    var feeP = 0.00;
    $('.tc-selected').each(function () {
        feeP = accAdd(feeP, parseFloat($(this).attr("data-value")))
    })

    var feeP2 = 0.00; //购物车提交
    $("em[id^='G_Postage_']").each(function () {
        feeP2 = accAdd(feeP2 , parseFloat($(this).text()));
    })

    feeP = (feeP2 > 0) ? feeP2 : feeP;

    paidAmount -= feeP;

    _max_pay = paidAmount;
    //如果积分最大抵抗的钱小于要支付的钱  那么取最大积分  否则根据要支付的钱来算积分
    _pay_n = (paidAmount/_jf_rate)>_jf_max?_jf_max:(paidAmount/_jf_rate);


    if($dkqUse.length > 0){
        _dpk_v = $("#cdkq").val();
        _max_pay -= _dpk_v;

        _pay_n = (_pay_n * _jf_rate > _max_pay) ? Math.ceil(_max_pay/_jf_rate) : _pay_n;
    }
    if(_max_pay != 0){
        $jfUse.attr("checked",true);
        var val = $(this).val();
        val = Math.min(val,_jf_max);

        val = Math.max(val, 0);
        val = Math.min(val,_pay_n);
        $(".costPoint").val(val)
    } else{
        $(".costPoint").val(0)
    }
    countAll();
})

// 更新积分方法
function updateJf(){
    var $dkqUse = $(".presentItem").find(".icon2:visible"); // 新版礼品券dom对象

    var _jf_rate = $(".costPoint").attr("data-rate")
    var _jf_max = $(".usablePoints").text();

    var paidAmount = 0;
    $('[id^=J_BundleSum_]').each(function () {
        paidAmount += parseFloat($(this).html());
    })

    //直接购买时一件商品的运费计算
    var feeP = 0.00;
    $('.tc-selected').each(function () {
        feeP = accAdd(feeP, parseFloat($(this).attr("data-value")))
    })

    var feeP2 = 0.00; //购物车提交
    $("em[id^='G_Postage_']").each(function () {
        feeP2 = accAdd(feeP2 , parseFloat($(this).text()));
    })

    feeP = (feeP2 > 0) ? feeP2 : feeP;

    paidAmount -= feeP;

    _max_pay = paidAmount;
    _pay_n = (paidAmount/_jf_rate)>_jf_max?_jf_max:(paidAmount/_jf_rate);


    if($dkqUse.length > 0){
        _dpk_v = $("#cdkq").val();
        _max_pay -= _dpk_v;

        _pay_n = (_pay_n * _jf_rate > _max_pay) ? Math.ceil(_max_pay/_jf_rate) : _pay_n;
    }

    if($jfUse.is(":checked")){
        $(".disPoint").html((_pay_n*_jf_rate).toFixed(2));
        $(".costPoint").val(_pay_n)
    } else {
       $(".costPoint").val(0);
       $("#J_UsePoints").attr("checked",false);
        $("#disPoint").html(0)
    }
    countAll();
}

// 更新礼品券信息
function updateLq(){
    var $dkqUse = $(".presentItem").find(".icon2:visible"); // 新版礼品券dom对象

    var paidAmount = 0;
    $('[id^=J_BundleSum_]').each(function () {
        paidAmount += parseFloat($(this).html());
    })

    //直接购买时一件商品的运费计算
    var feeP = 0.00;
    $('.tc-selected').each(function () {
        feeP = accAdd(feeP, parseFloat($(this).attr("data-value")))
    })

    var feeP2 = 0.00; //购物车提交
    $("em[id^='G_Postage_']").each(function () {
        feeP2 = accAdd(feeP2 , parseFloat($(this).text()));
    })

    feeP = (feeP2 > 0) ? feeP2 : feeP;
    paidAmount -= feeP;

    // 更新所有礼品券可使用金额
    $(".presentItem").each(function(){
          _dis = $(this).attr("data-dis");
         _e =  $(this).attr("data-mall");
         _max_kq_m = ((paidAmount*_dis/100) > _e )? _e : (paidAmount*_dis/100);
        _max_kq_m = (_max_kq_m*1).toFixed(2);
        $(this).parents(".presentItemBox").find("span.dislpq").html(_max_kq_m+"元");
    })

    if($dkqUse.length > 0){
        var  _dis = $dkqUse.parents(".presentItem").attr("data-dis");
        var _e = $dkqUse.parents(".presentItem").attr("data-mall");

        _max_kq_m = ((paidAmount*_dis/100) > _e )? _e : (paidAmount*_dis/100);
        _max_kq_m = (_max_kq_m*1).toFixed(2);

        $("#cdkq").val(parseFloat(_max_kq_m)).attr("data",parseFloat(_max_kq_m));
        $("#dkqId").val($dkqUse.parents(".presentItem").attr("data-id"));

        $dkqUse.parents(".presentItemBox").find("span.dislpq").html(_max_kq_m+"元");
    }else{
        $("#dkqId").val(0);
        $("#cdkq").val(0);
    }
    updateJf();
}


// 订单提交
$("#J_Go").click(function () {
    if(!$('div').hasClass('addr addr-cur') && !$('li').hasClass('choosed'))
    {
        $("#isAddress").show().find(".tc-feedback-content").html("请先填写收货地址");
        $('html,body').animate({scrollTop: $("#isAddress").offset().top}, 500);
        $("#J_Go").parent("span").addClass("go-disable");
        return false;
    }
   // if (parseInt($('input[name=shipRegionId]').val()) <= 0) return false;
    if($('#J_Go').parent("span").hasClass("tc-inputmask-active")){
        alert("留言字数不应超过200字");
        return false;
    }
    $('#J_Go').attr('disabled',true);
    $("#J_orderForm").submit();

});

$('.tc-counter').keyup(function(){
    checkWordLength(this)
})
$('.tc-counter').focus(function () {
    $(".tc-inputmask").find("label").hide();
    $('.tc-inputmask').addClass("tc-inputmask-active");
    $('.tc-counter-tip').css("display", "block");
});

$('.tc-counter').blur(function () {
    if (this.value == '') {
        $(".tc-inputmask").find("label").show();
        $('.tc-counter-tip').hide();
        $('.tc-inputmask').removeClass("tc-inputmask-active")
    }
});

function checkWordLength(obj) {
    var inside = '还可以输入<span><em></em><span>字</span></span>';
    var over = '已超出<span class="uic-err"></span>字';
    var val = obj.value;
    var len = Number(val.length);
    if (200 - len < 0) {
        $(".tc-counter-tip").empty().append(over);
        $(".tc-counter-tip").find(".uic-err").html(len - 200);
        $('#J_Go').parent("span").addClass("go-disable");
        return false;
    } else {
        $('#J_Go').parent("span").removeClass("go-disable");
    }
    return true;
}

// 2016-11 版本 立即购买
$(".discount").hover(function(){
    $(this).parent().find(".discountMessage").slideDown(200);
},function(){
    $(this).parent().find(".discountMessage").slideUp(200);
})

$(".J_icon1").each(function(index,dom){
    var a= $(this).parents(".presentItemBox").index()
    $(dom).mouseenter(function(){
        $(".messageTipsshow[data-id="+a+"]").show();
    })
})
$(".messageTipsshow").each(function(index,dom){
    //0-1-2-3
    //4-5-6-7
    //8-9-10-11

    //h -53  80

    var _f = Math.ceil((index+1)/4)
    var _h = -35 + 143 * (_f-1);
    if(index%4 == 0){
    }else if((index-1)%4 == 0){
        $(dom).css("left","301px");
    }else if((index+1)%4 == 0){
        $(dom).css("left","729px");
    }else{
        $(dom).css("left","514px");
    }

    $(dom).css("top",_h+"px");
})
$(".J_icon1").mouseleave(function(){
    $(".messageTipsshow").hide();
})

$("body").click(function(){
    $(".usepresent").slideUp(200);
})

$(".activityC").click(function(){
    var $This = $(this);
    var code = $.trim($(this).prev("input.fl").val());
    var sid = $(this).parents(".discountCouponActiveBox").find(".money_button").attr('data-storeid');

    var lineTr = $(this).parents('tr[data-order-total]');
    var orderTotal = parseFloat(lineTr.attr('data-order-total')); //店铺订购商品总价

    if (!lineTr[0]) {
        //立即购买
        orderTotal = parseFloat($('tr[data-order-total]').eq(0).attr('data-order-total'));
    }

    if(!code){
        layer.msg('优惠券码不能为空',{area: ['250px', '84px']})
        return false;
    }
    if(code.length != 16){
        layer.msg('优惠券码为16位，请重新输入',{area: ['250px', '84px']})
        return false;
    }

    $.ajax({
        url: 'index.php?app=member/BMember&act=activeCoupon2',
        data: {'code' : code,'sid' : sid,"money":orderTotal},
        type: 'post',
        dataType: 'json',
        success: function(data){
            var num = data[0];
            var msg = data[1];
            $(".usepresent_enterBox").append(num);

            $This.parents(".discountCouponActiveBox").find(".d9:last").trigger("click");

            layer.msg(msg,{area: ['250px', '84px']})
            return false;
        }
    })

})

$(".enteractive2").click(function () {
    var reason = $("#J_CloseReason").val();
    var pass = $("#TPL_password_1").val();
    //var code_card = $("#emailCaptcha").val();

    var lineTr = $(this).parents('tr[data-order-total]');
    var orderTotal = 0;

    if (!$(this).hasClass("cart")) {
        //立即购买
        orderTotal = parseFloat($('tr[data-order-total]').eq(0).attr('data-order-total'));
    }else{
        $(".other-line").each(function(){
            orderTotal = accAdd(orderTotal,$(this).attr("data-order-total"));//当前应支付商品价格
        })
    }

    if(reason==''||reason == undefined){
        layer.msg('请输入礼品券卡号',{
            area: ['250px', '84px']
        })
    } else if (pass==''||pass==undefined){
        layer.msg('请输入密码',{
            area: ['250px', '84px']
        })
    }
    // else if(code_card==''||code_card==undefined){
    //     layer.msg('请输入验证码',{
    //         area: ['250px', '84px']
    //     })
    // }
    else {
        $.get('index.php',{app:'member/BMember',act:'bindingCard2',cardId:reason,cardPs:pass,"money":orderTotal}, function(data) {
            if(data.err == 0) {
                /*$(".nocump").remove();
                layer.msg(data.msg,{
                    area: ['250px', '84px']
                })
                $("#lq_clear").before(data.html);
                $(".eachPresentList").show();*/
                $("input[name='lqid']").remove();
                $("#J_orderForm").append("<input type='hidden' value='"+data.nmnid+"' name='lqid'>");
                toggleLq(true);


            } else if(data.err == 8)  {
                layer.msg(data.msg,{
                    area: ['250px', '84px']
                })
            } else {
                layer.msg(data.msg,{
                    area: ['280px', '84px']
                })
            }
        },'json');
    }
})

//初始化更新优惠券
$(function () {
    var $This = $(".whatisthis > .d9.use-card-pre");
    $This.trigger("click");

    $(".whatisthis .aa9").hover(function(){
        $(this).find(".alert-box").show();
    },function(){
        $(this).find(".alert-box").hide();
    });


    $("#show_local_jf").click(function(){
        $(this).hide();
        $(".curr_jf").show();
    })
})


function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.pathname.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]); 
    }
    return null;
} 

function chooseLqConfirm(doc)
{
    if ($(doc).find('.icon2').hasClass('hidden')) {
        var lqid = $(doc).attr('data-id');
        $("[name='lqid']").remove();
        $("#J_orderForm").append("<input type='hidden' value='"+lqid+"' name='lqid'>");
        var flag = false; //true代表有选中的礼品券
        $(".icon2").each(function(){
            if (!$(this).hasClass('hidden')) {
                flag = true;
                return false;
            }
        });
        if (!flag) {
            $("#cover1").show();
        } else {
            toggleLq(true);
        }
        
    } else {
        toggleLq(false);
    }
}

function cancelLqConfirm()
{
    $("#cover2").show();
}

$(function(){
    $(".payAndvouchersMessages .jhlpq .btns").click(function(e){
        e.preventDefault();
        if(!$(this).parent(".jhlpq").hasClass("show")){
            $(this).parent(".jhlpq").addClass("show");
            $(this).parent(".jhlpq").next(".enterActive").slideDown(200);
        }else{
             $(this).parent(".jhlpq").removeClass("show");
            $(this).parent(".jhlpq").next(".enterActive").slideUp(200);
        }
    });

/*    var t_h = $(".float_area").offset().top;
    $(".float_area").css({
        position : "fixed",
    });
    $(window).scroll(function(){
        var top = $(document).scrollTop();
        if(top >= t_h - ($(window).height() -154)){
            $(".float_area").css({
                position : "relative",
            });
        }else{
            $(".float_area").css({
                position : "fixed",
            });
        }

        var scrollTop = $(this).scrollTop();
    　　var scrollHeight = $(document).height();
    　　var windowHeight = $(this).height();
    　　if(scrollTop + windowHeight == scrollHeight){ //页面最底部
    　　　　$('.float_area.bod .action').css({'box-shadow':'none'});
    　　}else{
            $('.float_area.bod .action').css({'box-shadow':'0px 0px 10px'});
        }
    });*/

    //关闭提示框
    $(".msg-cover a.close-btn,.msg-cover a.cancel").click(function(e){
        e.preventDefault();
        $(this).parents(".msg-cover").hide();
    });

    $(".enable_lq").click(function(){
        $(this).hide();
        $(".textcode").show();
    });

    $(".since li").click(function(){
        if(!$(this).hasClass("choosed")) {
            $(".since li input").attr("checked",false);
            $(this).find("input").attr("checked",true);
            $(".since li").removeClass("choosed");
            $(this).addClass("choosed");
            $(".addr").removeClass("addr-cur");
            $(".addr").addClass("addr-def");
            var frmAddress = $('#resetAddress');
            curAddrId = $(this).attr('data-id');
            frmAddress.find('input[name=addressId]').val("1_"+curAddrId);
            frmAddress.submit();
        }
    });

    //使用了礼品券
    if ($("#cdkq").val() > 0) {
        dkq = Number($("#cdkq").val());
        var order_total = 0;
        var notlast_dis = 0;
        //计算所有店铺不含运费的订单总价
        $(".grid-main").each(function(i,val){
            order_total += Number($(val).attr("data-order-total"));
        });
        //console.log(dkq);return false;
        $(".grid-main").each(function(k, grid){
            $(grid).find("td .tube-sum").each(function(i,val){
                og_total = Number($(val).find('p').text());
                og_dis = Number((og_total/order_total*dkq).toFixed(2));//优惠的价格
                diff = og_total-og_dis;//优惠后的价格
                notlast_dis += og_dis;
                var str = '<div class="triangle-down-discount">';
                str += '<div class="discountMessageBox">'
                str += '<div class="discountMessage">'
                str += '<span>礼品券抵扣</span>'
                str += '<div id="triangle-down"><span></span></div>'
                str += '</div>'
                str += '</div>'
                str += '<div class="favorable">'
                str += '<span>优惠'+og_dis+'元</span>'
                str += '</div>'
                str += '<p class="discount">礼品券</p>'
                str += '</div>';
                $(val).prev().html(str);
                str = '<p class="originalPrice">'+og_total+'</p><p class="sum">'+diff.toFixed(2)+'</p>';
                $(val).html(str);
            });
            notlast_dis = notlast_dis.toFixed(2);
            //去掉最后一个优惠的价格
            notlast_dis = (notlast_dis-og_dis).toFixed(2);

            //最后一个优惠的价格用减法算  否则四舍五入不准
            last_dis = (dkq-notlast_dis).toFixed(2);
            var str = '<div class="triangle-down-discount">';
            str += '<div class="discountMessageBox">'
            str += '<div class="discountMessage">'
            str += '<span>礼品券抵扣</span>'
            str += '<div id="triangle-down"><span></span></div>'
            str += '</div>'
            str += '</div>'
            str += '<div class="favorable">'
            str += '<span>优惠'+last_dis+'元</span>'
            str += '</div>'
            str += '<p class="discount">礼品券</p>'
            str += '</div>';
            $("td .tube-sum").last().prev().html(str);
            diff = og_total-last_dis;
            str = '<p class="originalPrice">'+og_total+'</p><p class="sum">'+diff.toFixed(2)+'</p>';
            $("td .tube-sum").last().html(str);
            if ($(grid).find(".sub-sel option:selected").length > 0) {
                post_fee = Number($(grid).find(".sub-sel option:selected").val());
            } else {
                post_fee = Number($(".tc-selected").attr("data-value"));
            }
            fk = (order_total-dkq+post_fee).toFixed(2);
            if ($(grid).find(".tc-rmb").length > 0) { //购物车结算
                $(grid).find(".tc-rmb").next().text(fk);
            } else { //立即购买
                $(".shopGross").text(fk);
            }
            
        });
    }
    
});

